<?php

require_once 'config.inc';
require_once('_db.inc');
require_once('_ui.inc');
require_once '_bank.inc';
// Create a database connection
$conn = db_connect(BANK_DB_USER, BANK_DB_PASSWORD);
ui_print_header('Bank - Verify Money Order');

	//verify signature
	echo "Verifying signature...<br><br>";
	if (!bank_verify_signature($_POST[bank_sig], $_POST[val], $_POST[unique_str], $conn)){
		echo "The signature of this money order is not valid!<br><br>";
	}else{
		
		echo "The signature of this money order is valid!<br><br>";
		
		//check uniqueness string with database
		echo "Checking uniqueness string against database...<br><br>";
		$moneyOrders = db_do_query($conn,"SELECT * FROM MO_DETAIL_BANK where UNIQUENESS_STRING='" .$_POST[unique_str] ."'");
					
		if (sizeof($moneyOrders)>0) {
		//if found, compare itendity string
			echo "This money order has been used<br><br>";
			$index = ID_index($_POST[selector_str],$moneyOrders[0][SELECTOR_STRING]);
			
			if ($index<0)
				//two selector string are the same
				echo "You are cheating!";
			else {
				// get the index-th id string
				$i = abs($index);
				$IDs = db_do_query($conn,"SELECT * FROM MO_IDSTRINGS_BANK WHERE UNIQUENESS_STRING='" .$_POST[unique_str] ."' and IDSTRING_N=" .$i);
				// combine two ID string to reveal ID
					$IDstr = join_id_string($_POST[IDstr][$i], $IDs[0][ID_STRING]);
				echo $IDstr . " is cheating!\n";
			}
			
		}
		else {

			echo "This money order is valid<br><br>";
		
			echo "Insert money order into database...<br><br>";
			$sql = "Insert into MO_DETAIL_BANK(UNIQUENESS_STRING, VAL, SELECTOR_STRING, CHEATED) values('"
				.$_POST[unique_str] ."', " .$_POST[val] .", " .$_POST[selector_str] .", 0)";
			$r = db_execute($conn, $sql);
			
			echo "Insert ID strings into database...<br><br>"; 
			if ($r){
				foreach ($_POST[IDstr] as $N => $ID){
					$sql = "Insert into MO_IDSTRINGS_BANK(UNIQUENESS_STRING, IDSTRING_N, ID_STRING) values('"
						.$_POST[unique_str] ."', " .$N .", '" .$ID ."')";
					$r = db_execute($conn, $sql);
				}
			}
			
			//add money to merchant account
			echo "Adding money to merchant's account<br><br>"; 
			update_Money('m', $_POST[val], '+', $conn);
//			$sql = "update accounts set balance=balance+$_POST[val] where  name='Customer-Alice'";
//			$r = db_execute($conn, $sql);
			
			//udate deposited tag
			//echo "Mark this money order as deposited</bt>";
			$conn1 = db_connect(MERCHANT_DB_USER, MERCHANT_DB_PASSWORD);
			db_execute($conn1, "UPDATE mo_detail_merchant set deposited=1 WHERE UNIQUENESS_STRING='" .$_POST[unique_str] ."'");
			oci_close($conn1);
		}
		
	}

	oci_close($conn);
	
ui_print_footer(date('Y-m-d H:i:s'));
?>